package com.lebang.medicalInquiry.utils;


import okhttp3.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

public class HttpClientUtil {


    // 单个生成配音
    public static InputStream generateVoice(String key, String name, String style, String volume, String rate, String role, String pitch, String styledegree, String text) {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        //91cfb97fd82446c98b2210e6e7b5f01f
        objectObjectHashMap.put("eastasia", "d99addf77b4b4ed0872c186267c82422");
        Object keyStr = objectObjectHashMap.get(key);
        String[] split = keyStr.toString().split(",");
        int index = ThreadLocalRandom.current().nextInt(0, split.length);
        keyStr = split[index];
        ResponseBody body = null;
//        pitch="-5%";
        try {
            OkHttpClient okHttpClient = OkhttpClientUtils.getInstance();
            String url = "https://" + key + ".tts.speech.microsoft.com/cognitiveservices/v1";

            String xml = XmlDomUtil.createDom1(name, style, volume, rate, pitch, styledegree, role, text);

//            if (TextUtil.isEmpty(xml)) {
//                return null;
//            }
            byte[] bytes = xml.getBytes();
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/ssml+xml"), bytes);
            Response execute = okHttpClient.newCall(new Request.Builder()
                    .addHeader("Content-Type", "application/ssml+xml")
                    .addHeader("X-Microsoft-OutputFormat", "audio-48khz-96kbitrate-mono-mp3")
//                    .addHeader("Authorization", "Bearer " + token)
                    .addHeader("User-Agent", "TTSAndroid")
                    .addHeader("Accept", "*/*")
                    .addHeader("content-length", String.valueOf(bytes.length))
                    .addHeader("Ocp-Apim-Subscription-Key", keyStr.toString())


                    .url(url)
                    .post(requestBody).build()).execute();
            body = execute.body();

            if (body != null) {
                InputStream inputStream = body.byteStream();
                ByteArray ba = new ByteArray();

                int rn2 = 0;
                int bufferLength = 4096;
                byte[] buf2 = new byte[bufferLength];
                while ((rn2 = inputStream.read(buf2, 0, bufferLength)) > 0) {
                    ba.cat(buf2, 0, rn2);
                }
                if (ba.getLength() == 0) {
                    //当前配音重试3次生成 如果不行跳过
                    for (int i = 0; i < 3; i++) {
                        InputStream repetition = repetition(okHttpClient, text, url, keyStr);
                        if (repetition != null) {
                            return repetition;
                        }
                    }
                }
                return new ByteArrayInputStream(ba.getArray());
            }
        } catch (IOException e) {
            return null;
        } finally {
            if (body != null) {
                body.close();
            }
        }
        return null;
    }

    public static InputStream repetition(OkHttpClient okHttpClient, String xml, String url, Object key) {
        ResponseBody body = null;
        try {


            byte[] bytes = xml.getBytes();
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/ssml+xml"), bytes);
            Response execute = okHttpClient.newCall(new Request.Builder()
                    .addHeader("Content-Type", "application/ssml+xml")
                    .addHeader("X-Microsoft-OutputFormat", "audio-24khz-48kbitrate-mono-mp3")
//                    .addHeader("Authorization", "Bearer " + token)
                    .addHeader("User-Agent", "TTSAndroid")
                    .addHeader("Accept", "*/*")
                    .addHeader("content-length", String.valueOf(bytes.length))
                    .addHeader("Ocp-Apim-Subscription-Key", key.toString())
                    .url(url)
                    .post(requestBody).build()).execute();
            body = execute.body();

            if (body != null) {
                InputStream inputStream = body.byteStream();
                ByteArray ba = new ByteArray();

                int rn2 = 0;
                int bufferLength = 4096;
                byte[] buf2 = new byte[bufferLength];
                while ((rn2 = inputStream.read(buf2, 0, bufferLength)) > 0) {
                    ba.cat(buf2, 0, rn2);
                }
                if (ba.getArray().length == 0) {
                    return null;
                }
                return new ByteArrayInputStream(ba.getArray());

            }
        } catch (IOException e) {
            return null;
        } finally {
            if (body != null) {
                body.close();
            }
        }
        return null;
    }


    public static void main(String[] args) {
        generateVoice("eastasia", "zh-CN-XiaoxiaoNeural", "", "100%", "50%", "", "", null, "我正在测试");
    }
}
